﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace ashx
{
    /// <summary>
    /// DownloadFile 的摘要说明
    /// </summary>
    public class DownloadFile : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request["UploadFileName"]))
            {
                try
                {
                    //下载图片                
                    //string filePath = context.Request["UploadFileName"].ToString().Replace("/", @"\");
                    string filePath = (context.Server.MapPath(context.Request["UploadFileName"].ToString())).Replace("ashx", @"Files\Templates");//这里注意了,你得指明要下载文件的路径.

                    if (System.IO.File.Exists(filePath))
                    {
                        FileInfo file = new FileInfo(filePath);
                        context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
                        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Server.UrlEncode(file.Name)); //解决中文文件名乱码    
                        context.Response.AddHeader("Content-length", file.Length.ToString());
                        context.Response.ContentType = "appliction/octet-stream";
                        context.Response.WriteFile(file.FullName);
                        context.Response.End();
                    }
                }
                catch { }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}